<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow
          header_list[e].value =
            header_list[e].type == 'input_number' ? ['', ''] : ''
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = item.type == 'input_number' ? ['', ''] : ''
        }),
          search_key()
      "
    ></search>
    <div class="p_0_10 bg_fff flex1">
      <div class="flex_js p_10_0">
        <div class="c_666 fw">企业查询</div>
        <div class="flex">
          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true
                })
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e
              }
            "
          ></setTable>
        </div>
      </div>
      <el-table
        style="text-align: center"
        :data="list"
        :max-height="max_height"
        border
        ref="table"
        highlight-current-row
        v-loading="loading"
        :default-sort="{ prop: '', order: '' }"
        :row-style="{
          height: height_size == 2 ? '50px' : '',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
        :row-class-name="
          ({ row, rowIndex }) => {
            row.index = rowIndex
          }
        "
        @row-click="
          (row) => {
            get_money(row)
          }
        "
      >
        <el-table-column
          type="index"
          label="序号"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="企业名称"
          width="200px"
          sortable
          prop="name"
          v-if="header_list[1].showTable"
          key="企业名称"
        >
          <template #default="scope: any">
            <div class="text_over" style="width: 100%">
              <el-tooltip :content="scope.row.name" placement="bottom">
                {{ scope.row.name }}
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="产品 - 等级"
          sortable
          v-if="header_list[0].showTable"
          key="产品 - 等级"
          width="220px"
        >
          <template #default="scope: any">
            <div v-show="scope.row?.threeDLevelId !== null">
              铝模设计平台 -
              <span v-for="item in enterprise_level_list" :key="item.id"
                ><span v-show="item.dictCode == scope.row.threeDLevelId">{{
                  item.dictValue
                }}</span>
              </span>
            </div>
            <div v-show="scope.row?.plugLevelId !== null">
              深化插件平台 -
              <span v-for="item in enterprise_level_list" :key="item.id"
                ><span v-show="item.dictCode == scope.row.plugLevelId">{{
                  item.dictValue
                }}</span>
              </span>
            </div>
            <div v-show="scope.row?.climbingLevelId !== null">
              爬架设计平台 -
              <span v-for="item in enterprise_level_list" :key="item.id"
                ><span v-show="item.dictCode == scope.row.climbingLevelId">{{
                  item.dictValue
                }}</span>
              </span>
            </div>
            <div v-show="scope.row?.digitalLevelId !== null">
              数字孪生平台 -
              <span v-for="item in enterprise_level_list" :key="item.id"
                ><span v-show="item.dictCode == scope.row.digitalLevelId">{{
                  item.dictValue
                }}</span>
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="社会统一信用代码"
          v-if="header_list[2].showTable"
          key="社会统一信用代码"
          prop="uniformCreditCode"
          width="180px"
          sortable
        ></el-table-column>
        <el-table-column
          label="企业住所"
          width="200px"
          v-if="header_list[3].showTable"
          key="企业住所"
          sortable
          prop="province"
        >
          <template #default="scope: any">
            <div class="text_over" style="width: 100%">
              <el-tooltip
                :content="
                  scope.row.province +
                  ' ' +
                  scope.row.city +
                  ' ' +
                  scope.row.district +
                  ' ' +
                  scope.row.detailAddress
                "
                placement="bottom-start"
              >
                {{ scope.row.province }} {{ scope.row.city }}
                {{ scope.row.district }} {{ scope.row.detailAddress }}
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="电话"
          v-if="header_list[4].showTable"
          key="电话"
          width="150px"
          sortable
          prop="telephone"
        ></el-table-column>

        <el-table-column
          label="用户数"
          v-if="header_list[5].showTable"
          key="用户数"
          width="100px"
          sortable
          prop="userNum"
        ></el-table-column>
        <el-table-column
          label="充值余额"
          v-if="header_list[6].showTable"
          key="充值余额"
          sortable
          prop="rechargeBalance"
        ></el-table-column>
        <el-table-column
          label="赠送余额"
          v-if="header_list[7].showTable"
          key="赠点余额"
          sortable
          prop="giftBalance"
        ></el-table-column>
        <el-table-column
          label="项目数量"
          v-if="header_list[8].showTable"
          width="120px"
          key="项目数量"
          sortable
          prop="projectNum"
        ></el-table-column>
        <el-table-column
          label="贡献值"
          sortable
          porp=""
          width="100px"
          v-if="header_list[9].showTable"
          key="贡献值"
        ></el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          width="100px"
          v-if="has_role_list[1].has_role"
        >
          <template #default="scope: any">
            <div class="flex_cc gap_20">
              <el-tooltip content="指定权限" placement="bottom">
                <svgBtn
                  icon="table_edit"
                  style="font-size: 20px"
                  @click="edit_role(scope.row)"
                  v-show="has_role_list[1].has_role"
                ></svgBtn>
              </el-tooltip>
              <el-tooltip
                content="营业执照"
                placement="bottom"
                v-if="
                  has_role_list[2].has_role && scope.row.businessLicense != ''
                "
              >
                <svgBtn
                  icon="table_info"
                  style="font-size: 20px"
                  @click="info_list(scope.row)"
                ></svgBtn>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="m_10_0 pagination"
        style="bottom: 177px"
        v-model:currentPage="form_data.current"
        v-model:page-size="form_data.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="
          (e) => {
            form_data.pageSize = e
            get_list()
          }
        "
        @current-change="
          (e) => {
            form_data.current = e
            get_list()
          }
        "
      />
      <div class="bottom_box">
        <div style="background-color: #f0f2f5; height: 10px"></div>
        <p class="fs_16">企业余额</p>
        <div>
          <div class="balance_1 c_fff">
            <div>
              <p>充值余额</p>
              <p class="fs_24">{{ money_list[0] }}</p>
            </div>
          </div>
          <div class="balance_3 c_fff">
            <div>
              <p>消费总额</p>
              <p class="fs_24">{{ money_list[2] }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <el-drawer
    v-model="show_box"
    direction="rtl"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <template #title><h4>权限分配</h4></template>
    <template #default>
      <el-tree
        class="tree"
        :data="role_list"
        show-checkbox
        node-key="id"
        ref="tree"
        :props="defaultProps"
      />
      <el-divider></el-divider>
      <div class="m_top10 tr">
        <el-button @click="show_box = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-drawer>
  <el-image-viewer
    v-if="img_url != ''"
    :url-list="[img_url]"
    fit="scale-down"
    class="border"
    append-to-body
    @close="img_url = ''"
  ></el-image-viewer>
</template>

<script lang="ts" setup>
import { check_role, dictData, handle_search_key } from '@/utils/utils' // 权限校验
import search from '@/view/components/search.vue'
import svgBtn from '@/components/svg_button.vue'
import setTable from '@/view/components/setTable.vue'
import { onMounted, ref, computed, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { useStore } from 'vuex'
const store = useStore()
// 页面权限组
const has_role_list = ref([
  { path: '', has_role: false },
  { path: 'enterprise/role', has_role: false },
  { path: 'enterprise/info', has_role: false },
])
const max_height = ref()
const list = ref()
const total = ref()
const loading = ref(false)
const height_size = ref(1)
const enterprise_level_list = ref([])
const header_list = ref<any>([
  {
    label: '产品 - 等级',
    value: [],
    showTable: true,
    type: '*select',
    isShow: true,
    options: computed(() => {
      return product_list.value
    }),
  },
  {
    label: '企业名称',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '社会统一信用代码',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
  {
    label: '企业住所',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
  {
    label: '电话',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },

  {
    label: '用户数',
    value: ['', ''],
    showTable: true,
    type: 'input_number',
    isShow: false,
    options: [],
  },
  {
    label: '充值余额',
    value: ['', ''],
    showTable: true,
    type: 'input_number',
    isShow: false,
    options: [],
  },
  {
    label: '赠送余额',
    value: ['', ''],
    showTable: true,
    type: 'input_number',
    isShow: false,
    options: [],
  },
  {
    label: '项目数量',
    value: ['', ''],
    showTable: true,
    type: 'input_number',
    isShow: false,
    options: [],
  },
  {
    label: '贡献值',
    value: ['', ''],
    showTable: true,
    type: 'input_number',
    isShow: false,
    options: [],
  },
])
const img_url = ref('')
const info_list = (e) => {
  axios
    .request({
      url: serviceApi.enterprise_downloadLicense + '/' + e.businessLicense,
      method: 'get',
      responseType: 'blob',
    })
    .then((res1) => {
      console.log(res1)
      const blob = new Blob([res1 as any]) // res.data 为接口返回的数据，依实例而行
      img_url.value = window.URL.createObjectURL(blob) // 生成一个 Blob URL
      //   const fileName =
      //     e.name + '-营业执照.' + e.businessLicense.split('.').at(-1)
      //   const listNode = document.createElement('a')
      //   listNode.download = fileName as any
      //   listNode.style.display = 'none'
      //   listNode.href = URL // 文件流生成的url
      //   document.body.appendChild(listNode)
      //   listNode.click() // 模拟在按钮上实现一次鼠标点击
      //   window.URL.revokeObjectURL(listNode.href) // 释放 URL 对象
      //   document.body.removeChild(listNode) // 移除 a 标签
    })
}
const table = ref(null)
const currentRowIndex = ref(0)
const show_box = ref(false)
const defaultProps = {
  // 权限树参数
  children: 'children',
  label: 'label',
  isLeaf: 'leaf',
}
const tree = ref(null)

const form_data = ref({
  current: 1,
  pageSize: 10,
  name: '',
  levelId: '',
  uniformCreditCode: '',
  rechargeBalance: '',
  giftBalance: '',
  address: '',
  telephone: '',
  projectNum: '',
  userNum: '',
})

onMounted(() => {
  max_height.value = window.innerHeight - 520 // 不带分页的 table 高度
  has_role_list.value.forEach((item) => {
    item.has_role = check_role(item.path)
  })
  EventBus.on('refresh', () => {
    get_list()
    ElMessage.success('刷新成功！')
  })
  get_list()
  get_role_list()
  dictData('1541679638193901569').then((res) => {
    console.log(res)
    ;(res as any).forEach((item) => {
      item.label = item.dictValue
      item.value = item.dictCode
    })
    enterprise_level_list.value = res as any
  }) // 获取字典值 企业等级
})
const product_list = computed(() => {
  let product_list = store.state.product_list
  product_list.forEach((item) => {
    item.children = enterprise_level_list.value.filter((item) => {
      return item.dictValue != '个人用户'
    })
  })
  console.log(product_list)
  return product_list
})
onUnmounted(() => {
  EventBus.off('refresh')
})

const submit = () => {
  var data = {
    enterpriseId: enterpriseId.value,
    routeIds: [],
  }
  var a = tree.value.getCheckedNodes(false, true) // 获取选中节点  包含半选中

  for (let i in a) {
    // 排除系统角色默认 权限
    if (!a[i].disabled) {
      data.routeIds.push(a[i].id)
    }
  }
  axios
    .request({ url: serviceApi.enterprise_role, method: 'post', data: data })
    .then((res) => {
      console.log(res)
      ElMessage.success('操作成功！')
      setTimeout(() => {
        show_box.value = false
        get_list()
      }, 1000)
    })
}
const enterpriseId = ref()
const edit_role = (e) => {
  axios
    .request({ url: serviceApi.enterprise_crud + '/' + e.id, method: 'get' })
    .then((res) => {
      console.log(res.data)
      let default_checked = []
      role_list.value = []
      let list = JSON.parse(JSON.stringify(base_role_list.value))
      list.forEach((item) => {
        let flag = res.data.commonRouteList.some((item1) => {
          return item1.id == item.id
        })
        if (flag) {
          default_checked.push(item.id)
          item.name = item.name + ' (系统)'
          item.disabled = true
        }
        let flag_1 = res.data.specialRouteList.some((item1) => {
          return item1.routeId == item.id
        })
        if (flag_1) {
          default_checked.push(item.id)
        }
      })
      role_list.value = arrToTree(list.reverse())
      enterpriseId.value = e.id
      show_box.value = true
      nextTick(() => {
        default_checked.forEach((item) => {
          let node = tree.value.getNode(item)
          if (node.isLeaf) {
            tree.value.setChecked(node, true)
          }
        })
      })
      show_box.value = true
    })
}
const money_list = ref([])
const get_money = (e) => {
  console.log(e)
  money_list.value = [
    e.rechargeBalance ? e.rechargeBalance : 0.0,
    e.giftBalance,
    e.costAmount ? e.costAmount : 0.0,
  ]
}
const get_list = () => {
  loading.value = true
  let obj = {
    plugLevelId:
      header_list.value[0].value[0] == 1 ? header_list.value[0].value[1] : '',
    threeDLevelId:
      header_list.value[0].value[0] == 2 ? header_list.value[0].value[1] : '',
    climbingLevelId:
      header_list.value[0].value[0] == 3 ? header_list.value[0].value[1] : '',
    digitalLevelId:
      header_list.value[0].value[0] == 4 ? header_list.value[0].value[1] : '',
  }
  let obj_keys = {}
  console.log(obj)
  for (let i in obj) {
    obj_keys[i] = {
      type: 'EQUAL',
      detailList: [{ value: obj[i].trim() }],
    }
  }
  axios
    .request({
      url: serviceApi.enterprise_list,
      method: 'post',
      data: Object.assign(obj_keys, handle_search_key(form_data.value)),
    })
    .then((res) => {
      if (!res.data.content.length) {
        list.value = []
        loading.value = false
        total.value = 0
        money_list.value = [0.0, 0.0, 0.0]
        return
      }

      table.value
        ? table.value.setCurrentRow(res.data.content[currentRowIndex.value])
        : ''
      money_list.value = [
        res.data.content[0].rechargeBalance
          ? res.data.content[0].rechargeBalance
          : 0.0,
        res.data.content[0].giftBalance ? res.data.content[0].giftBalance : 0.0,
        res.data.content[0].costAmount ? res.data.content[0].costAmount : 0.0,
      ]

      console.log(res)
      list.value = res.data.content
      total.value = parseInt(res.data.totalElements)
      loading.value = false
    })
    .catch((error) => {
      ElMessage.error(error)
      loading.value = false
    })
}
const search_key = () => {
  console.log(header_list.value)
  form_data.value = {
    current: 1,
    pageSize: 10,
    levelId: header_list.value[0].value[1],
    name: header_list.value[1].value,
    uniformCreditCode: header_list.value[2].value,
    address: header_list.value[3].value,
    telephone: header_list.value[4].value,
    userNum: header_list.value[5].value,
    rechargeBalance: header_list.value[6].value,
    giftBalance: header_list.value[7].value,
    projectNum: header_list.value[8].value,
  }
  get_list()
}
const role_list = ref()
const base_role_list = ref()
const get_role_list = () => {
  axios
    .request({ url: serviceApi.router_list, method: 'post' })
    .then((res) => {
      console.log(res)
      let list = (res.data = res.data.filter((item) => {
        return item.platformType != 1
      }))
      base_role_list.value = list
      console.log(role_list.value)
    })
    .catch((error) => {
      ElMessage.error(error)
    })
}
const arrToTree = (list) => {
  var map = {}
  var result = []
  list.forEach((item) => {
    map[item.id] = item
  })
  list.forEach((item) => {
    item.label = item.name
    item.value = item.id
    let parent = map[item.parentId]
    if (parent) {
      if (!parent.children) {
        parent.children = []
      }
      item = Object.assign(item, { leaf: true })
      parent.children.push(item)
    } else {
      item = Object.assign(item, { leaf: true })
      result.push(item)
    }
  })
  return result
}
</script>

<style lang="scss" scoped>
.balance_1 {
  display: flex;
  align-items: center;
  background-image: url('@/assets/img/enterprise_bg1.png');
  background-size: 100% 100%;
}
.balance_3 {
  display: flex;
  align-items: center;
  background-image: url('@/assets/img/enterprise_bg2.png');
  background-size: 100% 100%;
}
.bottom_box {
  position: absolute;
  bottom: 20px;
  left: 0;
  background-color: #fff;
  width: 100%;
  font-weight: bold;
  > p {
    font-size: 16px;
    margin: 15px 20px;
  }
  > div {
    display: flex;
    align-items: center;
    > div {
      display: flex;
      align-items: center;
      width: 220px;
      height: 96px;
      margin: 0 0 0 20px;
      > div {
        margin-left: 16px;
      }
    }
    > div p:first-child {
      font-size: 14px;
    }
    > div p:last-child {
      font-size: 24px;
      font-weight: bold;
    }
  }
}
.text_over {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
